package tcp;

import com.sun.deploy.xml.BadTokenException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 服务端
 */
public class TcpServerDemo01 {

    public static void main(String[] args) throws IOException {
        //1、服务端要有一个地址
        ServerSocket serverSocket = new ServerSocket(9999);
        Socket socket = null;
        InputStream inputStream = null;
        ByteArrayOutputStream byteArrayOutputStream = null;
        try {
            while (true) { //使用循环可以一直使服务端开启
                //2、等客户端连接（没有客户端发来的消息，会被阻塞）
                //这个socket就是客户端发送来的socket
                socket = serverSocket.accept();
                //3、读取客户端消息
                inputStream = socket.getInputStream();

                //使用管道流
                byteArrayOutputStream = new ByteArrayOutputStream();
                final byte[] buffer = new byte[1024];
                int len;
                while((len = inputStream.read(buffer)) != -1){
                    byteArrayOutputStream.write(buffer, 0, len);
                }
                System.out.println(byteArrayOutputStream);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭资源，先开后关
            if (byteArrayOutputStream != null) {
                byteArrayOutputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (socket != null) {
                socket.close();
            }
            if (serverSocket != null) {
                serverSocket.close();
            }
        }


    }
}
